package com.gitee.feizns.menu.boot;

import com.gitee.feizns.menu.intercetor.VerificationHandler;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * @author feizns
 * @since 2019/5/19 0019
 */
public class MenuAutoConfigurationImportSelector implements ImportBeanDefinitionRegistrar {

    private static final String PROPERTIES_ANNOTATION = EnablePermissionMenu.class.getName();

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        boolean definition = registry.containsBeanDefinition(MenuAutoConfiguration.class.getName());
        if ( definition == false ) {
            MenuProperties properties = createProperties(importingClassMetadata);
            AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(
                    MenuAutoConfiguration.class,
                    () -> new MenuAutoConfiguration(properties)).getBeanDefinition();

            registry.registerBeanDefinition(MenuAutoConfiguration.class.getName(), beanDefinition);
        }
    }

    private MenuProperties createProperties(AnnotationMetadata importingClassMetadata) {
        // Uncomfortable design
        Map<String, Object> attributes = importingClassMetadata.getAnnotationAttributes(
                PROPERTIES_ANNOTATION,
                false);

        MenuProperties properties = new MenuProperties();
        properties.setAnnotation((Class<? extends Annotation>) attributes.get("annotation"));
        Object handlerClass = attributes.get("handlerClass");
        if ( handlerClass != null ) {
            properties.setHandlerClass((Class<? extends VerificationHandler>[]) handlerClass);
        }

        return properties;
    }

}
